package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequirePermission(name = "角色查询", expression = "role:list")
    public String list(Model model, QueryObject qo) {
        model.addAttribute("pageInfo", roleService.query(qo));
        return "role/list";
    }

    @RequestMapping("/input")
    @RequirePermission(name = "角色编辑", expression = "role:saveOrUpdate")
    public String input(Model model, Long id) {
        // 查出所有权限
        model.addAttribute("permissions", permissionService.listAll());
        if (id != null) {
            // 查出单个role用于回显
            model.addAttribute("role", roleService.get(id));
            // 分配权限框的回显
            model.addAttribute("ownPermission", permissionService.queryByRoleId(id));
        }
        return "role/input";
    }

    @RequestMapping("/delete")
    @RequirePermission(name = "角色删除", expression = "role:delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list";
    }

    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "角色编辑", expression = "role:saveOrUpdate")
    // 因为一个角色的权限不止一个,所以用数组接收 权限id
    public String saveOrUpdate(Role role, Long[] permissionIds) { // permissionIds 要跟input前端一致
        if (role.getId() != null) {
            roleService.update(role,permissionIds);
        } else {
            roleService.insert(role,permissionIds);
        }
        return "redirect:/role/list";
    }

}
